//
//  HttpRequest.m
//  JCardAPP
//
//  Created by udkylin on 13-4-21.
//  Copyright (c) 2013年 freeguo. All rights reserved.
//
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
#import "HttpRequest.h"
#import "XMLReader.h"
#import "Global.h"
#import "ASIDownloadCache.h"

@implementation HttpRequest
@synthesize requestDelegate;

- (BOOL)addHttpRequest:(NSString *)action setPostData:(NSMutableDictionary *)dicData setTag:(NSString *)tag isGetMore:(BOOL)bMore
{
    NSString *preUrl = [NSString stringWithFormat:@"%@", WEB_URL];
    return [self addHttpRequest:action setPostData:dicData setTag:tag isGetMore:NO preUrl:preUrl];
}

- (BOOL)addHttpRequest:(NSString *)action setPostData:(NSMutableDictionary *)dicData setTag:(NSString *)tag isGetMore:(BOOL)bMore preUrl:(NSString *)preUrl
{
    if (! m_queue) {
        m_queue = [[ASINetworkQueue alloc]init];
        [m_queue reset];
        [m_queue setShowAccurateProgress:NO];
        [m_queue go];
        //init data cache path
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString* folderPath = [path stringByAppendingPathComponent:@"temp"];
        NSFileManager* fileManager = [NSFileManager defaultManager];
        BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
        if(! fileExists)
        {
            [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
    }
    
    if (bMore == YES) {
        [dicData setObject:total forKey:@"total"];
        [dicData setObject:downloads forKey:@"downloads"];
    }
    NSString* urlStr = [NSString stringWithFormat:@"%@%@", preUrl, action];
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *data = [dicData JSONString];
    NSData *aData = [data dataUsingEncoding:enc];
    NSMutableData *mData = [[NSMutableData alloc]init];
    mData = [NSMutableData dataWithData:aData];
    [request addRequestHeader:@"content-type" value:@"text/html"];
    [request setPostBody:mData];
    [request setPostLength:mData.length];
    [request setRequestMethod:@"POST"];
    [request setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:tag, @"tag", nil]];
    @try {
        [request setDelegate:self];
        //[request startAsynchronous];
        [m_queue addOperation:request];
    }
    @catch (NSException *exception) {
        NSLog(@"error name=%@,reason=%@", [exception name], [exception reason]);
        
        return FALSE;
    }
    @finally {
    }
    return TRUE;
}

+ (NSString *)genUrl:(NSString *)action userData:(NSMutableDictionary *)postData
{
    NSString *urlString = nil;
    if (![action hasPrefix:@"http:"])
    {
        urlString = [NSString stringWithFormat:@"%@%@", WEB_URL, action];
    }
    else
    {
        urlString = [NSString stringWithFormat:@"%@", action];
    }
    if (action == nil)
    {
        return urlString;
    }
    for (NSString *key in [postData allKeys])
    {
        urlString = [urlString stringByAppendingFormat:@"%@=%@&", key, [postData objectForKey:key]];
    }
    if ([[urlString substringFromIndex:(urlString.length - 1)] isEqualToString:@"&"])
    {
        urlString = [urlString substringToIndex:(urlString.length - 1)];
    }
    return urlString;
}

+ (NSDictionary *)startSyncHttpRequest:(NSString *)action setPostData:(NSMutableDictionary *)dicData
{
    NSURL *url = [NSURL URLWithString:action];
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"content-type" value:@"text/html"];
    [request setRequestMethod:@"GET"];
    [request startSynchronous];

    if ([request responseData] == nil)
    {
        return nil;
    }
    JSONDecoder *jd = [[JSONDecoder alloc] init];
    NSDictionary *ret = [jd objectWithData:[request responseData]];
    return ret;
}

+ (NSDictionary *)startSyncXMLHttpRequest:(NSString *)urlString
{
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", WEB_URL, urlString];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];

    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"content-type" value:@"text/html"];
    [request setRequestMethod:@"GET"];
    [request startSynchronous];
    
    NSData* resData = [request responseData];
    if (resData == nil)
    {
        return nil;
    }
    NSString *response = [[NSString alloc] initWithData:resData encoding:NSUTF8StringEncoding];
    NSDictionary *ret = [XMLReader dictionaryForXMLString:response error:nil];
    if ([[[ret objectForKey:@"root"] objectForKey:@"object"] isKindOfClass:[NSDictionary class]])
    {
        NSMutableArray *arrayo = [[NSMutableArray alloc] initWithObjects:[[ret objectForKey:@"root"] objectForKey:@"object"], nil];
        NSMutableDictionary *obj = [[NSMutableDictionary alloc] initWithObjectsAndKeys:arrayo, @"object", nil];
        
        NSMutableDictionary *root = [[NSMutableDictionary alloc] initWithCapacity:1];
        [root setObject:obj forKey:@"root"];
        return root;
    }
    return ret;
}

+ (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];

    return string;
}

+ (NSDictionary *)startSyncXMLHttpRequest:(NSString *)action setUserData:(NSMutableDictionary *)postData
{
    NSString *urlStr = [HttpRequest genUrl:action userData:postData];
    NSLog(@"%@", urlStr);

    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];

    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"content-type" value:@"text/xml"];
    [request setRequestMethod:@"GET"];
    request.timeOutSeconds =45;
    [request startSynchronous];

    NSData* resData = [request responseData];
    if (resData == nil)
    {
        return nil;
    }
//    NSLog(@"resData %@",[request responseString]);
    NSDictionary *temp = [XMLReader dictionaryForXMLData:resData error:nil];
    NSString *content = [[temp objectForKey:@"string"] objectForKey:@"text"]; 
    NSDictionary *ret = [XMLReader dictionaryForXMLString:content error:nil];

    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    for (NSString *key in [[ret objectForKey:@"NewDataSet"] allKeys])
    {
        if ([[[ret objectForKey:@"NewDataSet"] objectForKey:key] isKindOfClass:[NSDictionary class]])
        {
            NSMutableArray *arrayo = [[NSMutableArray alloc] initWithObjects:[[ret objectForKey:@"NewDataSet"] objectForKey:key], nil];
            [result setObject:arrayo forKey:key];
        }
        else
        {
            [result setObject:[[ret objectForKey:@"NewDataSet"] objectForKey:key] forKey:key];
        }
    }
    return result;
}

+ (NSDictionary *)startSyncJsonHttpRequest:(NSString *)action setUserData:(NSMutableDictionary *)postData
{
    NSString *urlStr = [HttpRequest genUrl:action userData:postData];
    NSLog(@"%@", urlStr);
    
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"content-type" value:@"text/xml"];
    [request setRequestMethod:@"GET"];
    request.useCookiePersistence = YES;
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths  objectAtIndex:0];
    NSString *filename=[path stringByAppendingPathComponent:@"cookie.plist"];
    NSDictionary *remData= [NSDictionary dictionaryWithContentsOfFile:filename];
    if (remData != nil)
    {
        NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:remData] autorelease];
        [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
    }
    [request startSynchronous];
    
    NSRange foundObj=[urlStr rangeOfString:KApiLogin options:NSCaseInsensitiveSearch];
    if(foundObj.length>0)
    {
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *path=[paths  objectAtIndex:0];
        NSString *filename=[path stringByAppendingPathComponent:@"cookie.plist"];
        [[request responseCookies] writeToFile:filename atomically:YES];

    }

    NSData* resData = [request responseData];
    JSONDecoder *jd = [[JSONDecoder alloc] init];
    NSDictionary *ret = [jd objectWithData:resData];
    return ret;
}


+ (NSDictionary *)startSyncHttpRequest:(NSString *)urlString
{
    NSLog(@"url %@",urlString);
    NSURL *url = [NSURL URLWithString:urlString];
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"content-type" value:@"text/html"];
    [request setRequestMethod:@"GET"];
    request.useCookiePersistence = YES;

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths  objectAtIndex:0];
    NSString *filename=[path stringByAppendingPathComponent:@"cookie.plist"];
    NSDictionary *remData= [NSDictionary dictionaryWithContentsOfFile:filename];
    if (remData != nil &&[[NSUserDefaults standardUserDefaults] boolForKey:@"isLoginKey"])
    {
        NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:remData] autorelease];
        [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
    }
    [request startSynchronous];

    
    NSArray *cookies = [request responseCookies];
    // 打印 sessionid
    NSHTTPCookie *cookie = nil ;
    for (cookie in cookies) {
        NSLog(@"1[cookie name] %@",[cookie name]);
    }
    
    NSData* resData = [request responseData];
    JSONDecoder *jd = [[JSONDecoder alloc] init];
    NSDictionary *ret = [jd objectWithData:resData];
    return ret;
}

-(void) requestFinished : (ASIHTTPRequest *)request
{
    NSData* resData = [request responseData];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *response = [[NSString alloc]initWithData:resData encoding:enc];
    NSData *blockdata = [response dataUsingEncoding:NSUTF8StringEncoding];
    JSONDecoder *jd = [[JSONDecoder alloc] init];
    NSDictionary *ret = [jd objectWithData:blockdata];
    
    NSString *tag = [[request userInfo] objectForKey:@"tag"];
    [self requestOK:tag responseDicData:ret];
}

-(void)requestFailed : (ASIHTTPRequest *)request
{
    NSString *tag = [[request userInfo] objectForKey:@"tag"];
    NSError* lastError = [request error];
    [self requestFail:tag errorObject:lastError];
}

- (void) requestOK:(NSString *)tag responseDicData : (NSDictionary *)dicData
{
    if (self.requestDelegate && [self.requestDelegate respondsToSelector:@selector(httpRequestOK:responseDicData:)])
    {
        [self.requestDelegate httpRequestOK:tag responseDicData:dicData];
    }
    else
        NSLog(@"default handle: requestOK tag=%@,data=%@", tag, dicData);
}

-(void) requestFail:(NSString *)tag errorObject:(NSError *)error
{
    NSLog(@"fail tag:[%@] error:[%@]", tag, error);
    if (self.requestDelegate && [self.requestDelegate respondsToSelector:@selector(httpRequestFail:errorObject:)]) {
        [self.requestDelegate httpRequestFail:tag errorObject:error];
    }
    else
        NSLog(@"default handle: requestFail tag=%@ error:%@", tag, error);
}

#pragma mark - 数据操作封装
- (BOOL)hasMoreData:(NSDictionary *)dicData
{
    total = [dicData objectForKey:@"total"];
    downloads = [dicData objectForKey:@"downloads"];
    if ([downloads intValue] >= [total intValue]) {
        //没有更多内容了
        return NO;
    } else {
        //后续还有数据
        return YES;
    }
}



+ (NSDictionary *)startSyncXMLMailHttpRequest:(NSString *)action setUserData:(NSMutableDictionary *)postData
{
    NSString *urlStr = [HttpRequest genUrl:action userData:postData];
    NSLog(@"%@", urlStr);
    
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"content-type" value:@"text/xml"];
    [request setRequestMethod:@"GET"];
    [request startSynchronous];
    
    NSData* resData = [request responseData];
    if (resData == nil)
    {
        return nil;
    }
    
    NSDictionary *temp = [XMLReader dictionaryForXMLData:resData error:nil];
    NSDictionary* ret = [temp objectForKey:@"GetMailResponse"];

    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    for (NSString *key in [[ret objectForKey:@"DataCollection"] allKeys])
    {
        if ([[[ret objectForKey:@"DataCollection"] objectForKey:key] isKindOfClass:[NSDictionary class]])
        {
            NSMutableArray *arrayo = [[NSMutableArray alloc] initWithObjects:[[ret objectForKey:@"DataCollection"] objectForKey:key], nil];
            [result setObject:arrayo forKey:key];
        }
        else
        {
            [result setObject:[[ret objectForKey:@"DataCollection"] objectForKey:key] forKey:key];
        }
    }
    
    return result;
}

+ (NSDictionary *)startSyncXMLGetUnReadHttpRequest:(NSString *)action setUserData:(NSMutableDictionary *)postData
{
    NSString *urlStr = [HttpRequest genUrl:action userData:postData];
    NSLog(@"%@", urlStr);
    
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
    request.shouldAttemptPersistentConnection = NO;
    [request addRequestHeader:@"content-type" value:@"text/xml"];
    [request setRequestMethod:@"GET"];
    [request startSynchronous];
    
    NSData* resData = [request responseData];
    if (resData == nil)
    {
        return nil;
    }


    NSDictionary* ret = [XMLReader dictionaryForXMLData:resData error:nil];

    
    return ret;
}

@end
